package com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.repository.HddcA1LiteraturedocumenttableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.repository.HddcA1LiteraturedocumenttableRepository;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.repository.entity.HddcA1LiteraturedocumenttableEntity;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.service.HddcA1LiteraturedocumenttableService;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.viewobjects.HddcA1LiteraturedocumenttableQueryParams;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.viewobjects.HddcA1LiteraturedocumenttableVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcA1LiteraturedocumenttableServiceImpl implements HddcA1LiteraturedocumenttableService {

	@Autowired
    private HddcA1LiteraturedocumenttableRepository hddcA1LiteraturedocumenttableRepository;
    @Autowired
    private HddcA1LiteraturedocumenttableNativeRepository hddcA1LiteraturedocumenttableNativeRepository;

    @Override
    public JSONObject queryHddcA1Literaturedocumenttables(HddcA1LiteraturedocumenttableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcA1LiteraturedocumenttableEntity> hddcA1LiteraturedocumenttablePage = this.hddcA1LiteraturedocumenttableNativeRepository.queryHddcA1Literaturedocumenttables(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcA1LiteraturedocumenttablePage);
        return jsonObject;
    }


    @Override
    public HddcA1LiteraturedocumenttableEntity getHddcA1Literaturedocumenttable(String id) {
        HddcA1LiteraturedocumenttableEntity hddcA1Literaturedocumenttable = this.hddcA1LiteraturedocumenttableRepository.findById(id).orElse(null);
         return hddcA1Literaturedocumenttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcA1LiteraturedocumenttableEntity saveHddcA1Literaturedocumenttable(HddcA1LiteraturedocumenttableEntity hddcA1Literaturedocumenttable) {
        String uuid = UUIDGenerator.getUUID();
        hddcA1Literaturedocumenttable.setUuid(uuid);
        hddcA1Literaturedocumenttable.setCreateUser(PlatformSessionUtils.getUserId());
        hddcA1Literaturedocumenttable.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcA1Literaturedocumenttable.setIsValid("1");
        this.hddcA1LiteraturedocumenttableRepository.save(hddcA1Literaturedocumenttable);
        return hddcA1Literaturedocumenttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcA1LiteraturedocumenttableEntity updateHddcA1Literaturedocumenttable(HddcA1LiteraturedocumenttableEntity hddcA1Literaturedocumenttable) {
        HddcA1LiteraturedocumenttableEntity entity = hddcA1LiteraturedocumenttableRepository.findByUuidAndIsValid(hddcA1Literaturedocumenttable.getUuid(), "1");
        UpdateUtil.copyNullProperties(entity, hddcA1Literaturedocumenttable);
        hddcA1Literaturedocumenttable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcA1Literaturedocumenttable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcA1LiteraturedocumenttableRepository.save(hddcA1Literaturedocumenttable);
        return hddcA1Literaturedocumenttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcA1Literaturedocumenttables(List<String> ids) {
        List<HddcA1LiteraturedocumenttableEntity> hddcA1LiteraturedocumenttableList = this.hddcA1LiteraturedocumenttableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcA1LiteraturedocumenttableList) && hddcA1LiteraturedocumenttableList.size() > 0) {
            for(HddcA1LiteraturedocumenttableEntity hddcA1Literaturedocumenttable : hddcA1LiteraturedocumenttableList) {
                hddcA1Literaturedocumenttable.setIsValid("0");
                hddcA1Literaturedocumenttable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Literaturedocumenttable.setUpdateTime(new Date());
                this.hddcA1LiteraturedocumenttableRepository.save(hddcA1Literaturedocumenttable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcA1LiteraturedocumenttableQueryParams queryParams, HttpServletResponse response) {
        List<HddcA1LiteraturedocumenttableEntity> yhDisasterEntities = hddcA1LiteraturedocumenttableNativeRepository.exportYhDisasters(queryParams);
        List<HddcA1LiteraturedocumenttableVO> list=new ArrayList<>();
        for (HddcA1LiteraturedocumenttableEntity entity:yhDisasterEntities) {
            HddcA1LiteraturedocumenttableVO yhDisasterVO=new HddcA1LiteraturedocumenttableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"文献资料库","文献资料库",HddcA1LiteraturedocumenttableVO.class,"文献资料库.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
            try {
                // 返回的消息
                StringBuilder returnMsg = new StringBuilder();
                // 导入的参数信息
                ImportParams params = new ImportParams();
                // 设置简析的第一行
                params.setHeadRows(1);
                // 是否需要校验
                params.setNeedVerify(true);
                // 获取到Excel数据
                ExcelImportResult<HddcA1LiteraturedocumenttableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcA1LiteraturedocumenttableVO.class, params);
                List<HddcA1LiteraturedocumenttableVO> list = result.getList();
                // Excel条数据
                //int firstList = list.size();
                StringBuilder sb = new StringBuilder();
                //保存
                saveDisasterList(list, sb);
                returnMsg.append("成功导入" + (result.getList().size() ));
                returnMsg.append(sb);
                if (result.isVerifyFail()) {
                    // 校验返回失败行信息
                    Iterator<HddcA1LiteraturedocumenttableVO> iterator = result.getFailList().iterator();
                    while (iterator.hasNext()) {
                        HddcA1LiteraturedocumenttableVO yhDisasterVO = iterator.next();
                        String error = "";
                        returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                        returnMsg.append(error);
                    }
                }
                return returnMsg.toString();
            } catch (Exception e) {

                return "导入失败，请检查数据正确性";
            }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcA1LiteraturedocumenttableVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcA1LiteraturedocumenttableEntity yhDisasterEntity = new HddcA1LiteraturedocumenttableEntity();
            HddcA1LiteraturedocumenttableVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcA1Literaturedocumenttable(yhDisasterEntity);
        }
    }
}
